package com.hd.trans.share;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 音频相关文件读写类
 */
public class FileRWExtUtil {



    /**
     * 读取txt文件
     *
     * @param filePath 输入文件路径
     * @return
     */
    public static String readFileOnLine(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return "";
        }

        StringBuilder fileContent = new StringBuilder();
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {

            inputStreamReader = new InputStreamReader(new FileInputStream(filePath));
            bufferedReader = new BufferedReader(inputStreamReader);
            String line = "";
            while (true){
                line = bufferedReader.readLine();
                if(line !=null){
                    fileContent.append(line).append("\n");
                }else{
                    break;
                }
            }
        } catch (Exception e) {
            // do nothing
            e.printStackTrace();
        } finally {
            try {
                if(bufferedReader!=null){
                    bufferedReader.close();
                }
                if(inputStreamReader!=null){
                    inputStreamReader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return fileContent.toString();
    }

    public static List<Short> shortArrayToList(short[] shorts) {
        List<Short> shortList = new ArrayList<>();
        for (short s : shorts) {
            shortList.add(s);
        }
        return shortList;
    }

    public static List<Short> readFileOnShortList(String filePath){
        if(TextUtils.isEmpty(filePath)){
            return new ArrayList<>();
        }
        short[] shorts = readFileOnShortArray(filePath);
        if(shorts==null){
            return new ArrayList<>();
        }
        List<Short> shortList = new ArrayList<>();
        for (short s : shorts){
            shortList.add(new Short(s));
        }
        return shortList;
    }

    private static short[] readFileOnShortArray(String filePah){
        File file = new File(filePah);
        byte[] fdata = null;
        try {
            FileInputStream fs = new FileInputStream(file);
            FileChannel channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while (channel.read(byteBuffer) > 0) {
                fdata = byteBuffer.array();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        short[] drawingData = bytesToShort(fdata,ByteOrder.LITTLE_ENDIAN);
        return drawingData;
    }

    private static short[] bytesToShort(byte[] bytes, ByteOrder byteOrder){
        short[] shortsByte = null;
        if(bytes==null){
            return null;
        }
        Log.d("TAG","bytes---->"+bytes.length);
        shortsByte = new short[bytes.length / 2];
        ShortBuffer shortBuffer = ByteBuffer.wrap(bytes).order(byteOrder).asShortBuffer();
        for (int i=0;i<shortsByte.length;i++){
            shortsByte[i] = shortBuffer.get(i);
        }
        // 报错 UnsupportedOperationException
//        shortsByte = shortBuffer.array();

        return shortsByte;
    }

    public static boolean saceToText(Object object,String path){
        String jsonStr = new Gson().toJson(object);
        return saveText(jsonStr,path);
    }

    /**
     * 保存 txt文件
     * @param content
     * @param path
     * @return
     */
    public static boolean saveText(String content,String path){
        boolean reuslt = true;
        FileOutputStream fileOutputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
            bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(content);
            bufferedWriter.flush();
            outputStreamWriter.flush();
            fileOutputStream.flush();

        } catch (Exception e) {
            reuslt = false;
            Log.e("TAG", "saveText--------------error--->"+e);
        } finally {
            try {
                if(fileOutputStream!=null){
                    fileOutputStream.close();
                }
                if(outputStreamWriter!=null){
                    outputStreamWriter.close();
                }
                if(bufferedWriter!=null){
                    bufferedWriter.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }

        }
        return reuslt;
    }

    /**
     * 读取文件中的json数据
     * @param filePath
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T readFile(String filePath,Class<T> cls){
        try {
            String json = readFileOnLine(filePath);
            return new Gson().fromJson(json,cls);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


}
